import { OnInit, OnChanges, OnDestroy, Component, ChangeDetectionStrategy, ViewEncapsulation, Input, TemplateRef, NgZone, ViewChild, ElementRef } from '@angular/core';
import { InputNumber, InputBoolean } from 'ng-zorro-antd';
import { Lbchart } from '@shared';
import { Subscription } from 'rxjs';
import { SupData } from '@core/lb/SupData';
/**
 * 数据卡片
 */
@Component({
  selector: 'lb-data-card',
  templateUrl: './lb-data-card.component.html',
  styleUrls: ['./lb-data-card.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush, // 检测改为按需，即不自动刷新
})
export class LbDataCardComponent implements OnInit, OnChanges, OnDestroy, Lbchart {
  private chart: any;
  private resize$: Subscription;
  @ViewChild('datacard', { static: true }) private node: ElementRef;
  @Input() padding: Array<number | string> | string = 'auto';
  @Input() @InputNumber() delay = 0;
  @Input() color: string[] = null;
  @Input() colorFiled = 'name';
  @Input() position: any

  @Input() style: { [key: string]: string };
  @Input() xcolors: Array<string>
  @Input() ycolors: Array<string>

  @Input() aliasoption: object
  // @Input() position: {x: string, y: string} = {x: 'genre', y: 'sold'}

  @Input() data: any[]

  // @Input() width: number;
  @Input() height: number;

  @Input() @InputBoolean()  legendshow = false;

  @Input() @InputBoolean() tooltipshow;
  @Input() @InputBoolean() tooltipshowtitle;
  @Input() @InputBoolean() tooltipshowpercent;

  @Input() pillarcolor

  @Input() sortx = true
  @Input() sortz
  @Input() sortrule = 'ASC'

  constructor(private ngZone: NgZone, private supdata: SupData) { }

  commonStyleHandle(chart, data) {
    // 计算百分比
    const dv = new DataSet.View().source(data);  

    console.log(dv.rows)
    chart.source(dv.rows)

    // 图例不显示
    if(!this.legendshow) {
      chart.legend(false)
    }

    if (this.tooltipshow) {
      chart.tooltip({
        showTitle: this.tooltipshowtitle,
        itemTpl: '<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}'+ (this.tooltipshowpercent? '({percent}%)': '') + '</li>'
      });
    } else {
      chart.tooltip(false);
    }

    return dv.rows;
  }
  
  install(resdata) {
    // 图表信息
    const dataFilds: string[] = resdata.message.tb.DAA035.split(',');
    const groupFileds: string[] = resdata.message.tb.DAA036.split(',');
    // 数据处理
    let data = this.supdata.rebuildData(resdata.message.data, resdata.message.tb, groupFileds, groupFileds);
    // 字典转化
    data = this.supdata.rebuildDsDataToLabel(data);
    this.data = data;
    this.position = { x: groupFileds[0], y: dataFilds[0] };
    this.render();
  }

  render() {
    const { node, padding } = this;
    const container = node.nativeElement as HTMLElement;

    const chart = (this.chart = new G2.Chart({
      container,
      forceFit: true,  // 图表的宽度自适应开关
      height: this.getHeight(),
      padding,
    }));

    this.commonStyleHandle(chart, this.data)

    const rchart = 
    chart
      .interval()
      .position(`${this.position.x}*${this.position.y}`)
      .color(this.position.x, x => {
        return this.pillarcolor
      })

    chart.render();
  }

  attachChart() {
    const { chart, padding, data, color } = this;
    if (!chart || !data || data.length <= 0) return;

    this.commonStyleHandle(chart, this.data)
    
    const height = this.getHeight();
    if (chart.get('height') !== height) {
      chart.changeHeight(height);
    }

    chart.set('padding', padding);
    chart.changeData(data);
  }

  destroy() {
    if (this.resize$) {
      this.resize$.unsubscribe();
    }
    if (this.chart) {
      this.ngZone.runOutsideAngular(() => this.chart.destroy());
    }
  }

  /**
   * 报表高度
   * 存在报表头，则需要减掉报表头的高度
   */
  getHeight() {
    return this.height
    // return this.title ? (this.height - TITLE_HEIGHT) : this.height;
  }


  ngOnInit(): void {
    if (this.position && this.data.length > 0) {
      this.ngZone.runOutsideAngular(() => setTimeout(() => this.render(), this.delay));
    }

  }

  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    this.ngZone.runOutsideAngular(() => this.attachChart());
  }

  ngOnDestroy(): void {
    this.destroy();
  }
}